import { _decorator, Component, Rect, UITransform, Node } from 'cc';
import { MoonGame } from '../MoonGame';
import { Enemy, ENEMY_STAT } from './Enemy';
const { ccclass, property } = _decorator;

@ccclass('Bullet')
export class Bullet extends Component {

    private enemySet: Node[]

    private speedX: number

    private speedY: number

    onLoad(): void {
        this.enemySet = this.node.parent.parent.getComponent(MoonGame).enemySet;
        this.speedX = 0;
        this.speedY = 500
    }

    update(deltaTime: number) {
        let pos = this.node.getPosition()
        let newPos = pos.add3f(this.speedX * deltaTime, this.speedY * deltaTime, 0)
        if (newPos.y >= 500) {
            this.node.removeFromParent()
            return;
        }
        this.node.setPosition(newPos)
        // 判断是否击中敌人
        let bulletBox = this.node.getComponent(UITransform).getBoundingBoxToWorld()
        if (this.enemySet) {
            this.enemySet.forEach((enemy: Node) => {
                if (this.checkHit(bulletBox, enemy)) {
                    enemy.getComponent(Enemy).onHurt()
                    this.node.removeFromParent()
                    return;
                }
            })
        }
    }

    checkHit(bulletBox: Rect, enemy: Node) {
        if (enemy.getComponent(Enemy).state !== ENEMY_STAT.LIVE) {
            return;
        }
        let enemyBox = enemy.getComponent(UITransform).getBoundingBoxToWorld()
        return bulletBox.intersects(enemyBox)
    }

}

